package com.cow.sram.module.archives;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cow.framework.core.base.BaseComponent;
import com.cow.framework.core.exception.BusinessException;
import com.cow.framework.utils.convert.ConvertUtil;
import com.cow.sram.comm.config.constant.MessageConstants;
import com.cow.sram.comm.config.tree.TreeDefService;
import com.cow.sram.data.dto.User;
import com.cow.sram.data.entity.Orginfo;
import com.cow.sram.data.entity.Resourceinfo;
import com.cow.sram.data.entity.TreeDef;
import com.cow.sram.module.distribution.RoleResourceService;
import com.cow.sram.module.managerResource.ResourceinfoService;

/**
 * 组织管理
 * @author Administrator
 *
 */
@RestController
@EnableAutoConfiguration
@Transactional
@RequestMapping(value="/archives")
public class OrgInfoController extends BaseComponent{

	@Autowired
	OrgInfoService orginfoService;
	@Autowired
	ResourceinfoService resourceinfoService;
	@Autowired
	private TreeDefService treeDefService;
	@Autowired
	RoleResourceService roleResourceService;

	/**获取权限内组织*/
	@RequestMapping(value="/getMyOrgTree")	
	public Object getMyOrgNode() throws Exception{		
//		List<com.cow.support.entity.Resourceinfo> orgList = super.getCurUser().getResourceMap().get("t10");//部门权限	
		List<Resourceinfo> orgList =orginfoService.queryUserOrg(); //部门权限		
		List<TreeDef> treeList = convertResourceToTree(orgList);				
		treeList = listToTree(treeList);
		return treeList;
	}
	
	private List<TreeDef> convertResourceToTree(List<Resourceinfo> orgList){
		List<TreeDef> treeDefList = new ArrayList<TreeDef>();		
		//转为tree
		for(Resourceinfo resource:orgList){
			TreeDef tree = new TreeDef();
			tree.setDataType(resource.getResourcetype());
			tree.setNodeId(resource.getResourceid());
			tree.setNodeName(resource.getName());
			tree.setSubsidiary1(resource.getSubsidiary1());
			tree.setSubsidiary2(resource.getSubsidiary2());
			tree.setFatherId(resource.getFatherId());
			if(resource.getValidFlag() == null){
				tree.setValidFlag(1);
			}
			treeDefList.add(tree);
		}		
		return treeDefList;
	}
	
	/**
	 * 资源列表转树形结构
	 * @param list
	 * @return
	 * Administrator
	 */
	public List<TreeDef> listToTree(List<TreeDef> list){
		List<TreeDef> resultList = new ArrayList<TreeDef>();
		if (list != null) {
			for (TreeDef resourceinfo : list) {				
				for (TreeDef resource : list) {	
					if(resource.getSubsidiary5() != null){//有父节点
						continue;
					}
						
					if (resource.getFatherId().equals(resourceinfo.getNodeId())) {
						resource.setSubsidiary5("hasFather");
						if (resourceinfo.getChildList() == null ) {
							List<TreeDef> myChildrens = new ArrayList<TreeDef>();
							myChildrens.add(resource);
							resourceinfo.setChildList(myChildrens);
						}else{
							resourceinfo.getChildList().add(resource);
						}
					}				
				}
			}
			
			for (TreeDef resourceinfo : list) {
				if (resourceinfo.getSubsidiary5() == null) {//最上级节点
					resultList.add(resourceinfo);
				}				
			}
		}
		return resultList;
	}
	

	
	/**获取树形定义*/	
	private List<Resourceinfo> getAllChild(String dataType,Integer pid,String isQuery){	
		String treeType;
		if(isQuery.equals("1")){
			treeType =  "treeDef-all";
		}else{
			treeType =  "treeDef";
		}
		
		List<Resourceinfo> resourceList = (List<Resourceinfo>)super.getCache(treeType, dataType+"-"+ConvertUtil.nvl(pid,""));
		
		if(resourceList != null){
			List<Resourceinfo> tmpTreeList = new ArrayList<Resourceinfo> ();		
			tmpTreeList.addAll(resourceList);
			for(Resourceinfo treeDef:tmpTreeList){
				if("general,areaNet".contains(super.getCurUser().getOrgInfoDTO().getOrgtype()) && "areaMarket,market".contains(treeDef.getSubsidiary2())){
					resourceList.remove(treeDef);
					continue;
				}
				
				if("areaMarket,market".contains(super.getCurUser().getOrgInfoDTO().getOrgtype()) && "general,areaNet".contains(treeDef.getSubsidiary2())){
					resourceList.remove(treeDef);
					continue;
				}
				
				List<Resourceinfo> childList = getAllChild(treeDef.getResourcetype(),treeDef.getResourceid(),isQuery);
				if(childList != null){
					treeDef.setChildList(childList);
				}
			}
		}
		
		return resourceList;
	}
	
	/**ID查询*/
	@RequestMapping(value="/getOrgById")
	public Object getOrgById(@RequestParam Integer id){
		return orginfoService.getOrgById(id);
	}
	
	/**增加*/
	 @RequestMapping(value="/newOrgInfo")
	 public Object newOrgInfo(@RequestBody Orginfo org){	 

		//改为保存到资源表
		Resourceinfo rsc = new Resourceinfo();
		rsc.setResourcetype("t10");
		rsc.setFatherId(org.getSuperorgid());
		rsc.setIsTree(1);
		rsc.setValidFlag(1);
		rsc.setName(org.getOrgname());
		rsc.setSubsidiary1(orginfoService.getMaxOrgCode(org.getSuperorgid()));
		rsc.setSubsidiary2(org.getOrgtype());
		rsc.setSubsidiary3(org.getDescription());
		
		rsc.setSubsidiary4(org.getTaxpayerid()); //纳税人识别号
		rsc.setSubsidiary5(org.getTaxpayername()); //纳税人名称
		rsc.setSubsidiary6(org.getTradecode()); //行业代码
		rsc.setSubsidiary7(org.getRegtype()); //登记注册类型
		rsc.setSubsidiary8(org.getBodytype()); //课税主体类型
		rsc.setSubsidiary9(org.getBusiarea()); //经营范围
				
		rsc.setSystemid("comm");//公共资源
		
		resourceinfoService.saveResourceInfo(rsc);
		
		//更新缓存
		treeDefService.addTreeNodeCache(rsc);
		
		return rsc.getResourceid();
	 }
	
	/**编辑*/
	@RequestMapping(value="/editOrgInfo")
	public Object editOrgInfo(@RequestBody Map parmMap){
		Orginfo org = orginfoService.getOrgById(Integer.valueOf(parmMap.get("orgid").toString()));
		Resourceinfo rsc = resourceinfoService.getResourceinfoID(org.getOrgid());
		rsc.setName((String)parmMap.get("orgname"));
		rsc.setSubsidiary1((String)parmMap.get("orgcode"));
		rsc.setSubsidiary2((String)parmMap.get("orgtype"));
		rsc.setSubsidiary3((String)parmMap.get("description")); //组织描述
//		if(rsc.getFatherId()!=null){
//			
//		}
		resourceinfoService.saveResourceInfo(rsc);//modified by yangsj 2017-6-20
		//更新缓存
		treeDefService.updateTreeNodeCache(rsc);
		return "success";
	}
	 
	/**删除*/
	@RequestMapping(value="/delOrgInfo")
	public Object delOrgInfo(@RequestParam Integer id){
		//获取组织下的用户
		List<User> userList = super.getAuthClient().getOrgUser(id);
		if(userList != null && !userList.isEmpty()){
			throw new BusinessException("B1016",MessageConstants.B1016);
		}
		
		Resourceinfo rsc = resourceinfoService.getResourceinfoID(id);
		if(super.getCache("treeDef", "t10-"+id)==null){
			//更新缓存
			treeDefService.delTreeNodeCache(rsc);
			roleResourceService.delByResourceId(id);
			resourceinfoService.delResourceInfo(id);
		}else{
			throw new BusinessException("B1015",MessageConstants.B1015);
		}
		return "success";
	}
}
